package com.tanhua.server.controller;

import com.tanhua.domain.mongo.UserFreeze;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.dubbo.api.UserFreezeApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 评论控制器
 */
@RestController
@RequestMapping("/comments")
@Slf4j
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Reference
    private UserFreezeApi userFreezeApi;

    /**
     * 接口名称：评论列表
     * 接口路径：GET/comments
     */
    @GetMapping
    public ResponseEntity<Object> queryCommentsList(@RequestParam(defaultValue = "1") Integer page,
                                                    @RequestParam(defaultValue = "10") Integer pagesize,
                                                    String movementId) throws Exception{
        log.info("接口名称：评论列表");
        return commentService.queryCommentsList(page, pagesize, movementId);
    }

    /**
     * 接口名称：评论-提交
     * 接口路径：POST/comments
     */
    @PostMapping
    public ResponseEntity<Object> saveComments(@RequestBody Map<String, String> param) throws Exception {
        log.info("接口名称：评论-提交");
        String movementId = param.get("movementId");
        String content = param.get("comment");
        Long userId = UserHolder.getUserId();
        UserFreeze userFreeze = userFreezeApi.queryFreezeDetailById(userId.intValue());
        if (userFreeze == null || userFreeze.getFreezingRange() == 0) {
            return commentService.saveComments(movementId, content);
        } else {
            if (userFreeze.getFreezingRange() != 0) {
                return ResponseEntity.status(500).body(ErrorResult.freezeCommentError(userFreeze.getReasonsForFreezing()));
            } else {
                return commentService.saveComments(movementId, content);
            }
        }
    }

    /**
     * 接口名称：评论-点赞
     * 接口路径：GET/comments/:id/like
     */
    @GetMapping("/{id}/like")
    public ResponseEntity<Object> likeComments(@PathVariable String id) throws Exception{
        log.info("接口名称：评论-点赞");
        return commentService.likeComments(id);
    }
    /**
     * 接口名称：评论-取消点赞
     * 接口路径：GET/comments/:id/dislike
     */
    @GetMapping("/{id}/dislike")
    public ResponseEntity<Object> unlikeComments(@PathVariable String id) throws Exception{
        log.info("接口名称：评论-点赞");
        return commentService.unLikeComments(id);
    }

}
